<template>
  <table-easy :list="list.list"
              ref="tableRef"
              :columns="columns"
              :filterArr="filterArr"
              :tableType="tableType"
              :showIndex="true"
              :showSelect="true"
              @changeSelect="changeSelect"
              :default-sort="{ prop: 'date', order: 'descending' }"
              :showPagination="true"
              :showBatchAction="true"
              @updateList="updateList"
              row-key="id"
              :total="total">
    <!-- 表头插槽 -->
    <template #index>序号</template>
    <template #head_name>
      <tool-tip content="微信唯一标识或头像+昵称">
        <el-icon style="{position:relative;top:2px;}"><QuestionFilled /></el-icon>
      </tool-tip>
    </template>
    <!-- 表格插槽 -->
    <template #name="{row}">
      <div v-if="row.avatar || row.nickName" :style="{display:'flex',alignItems:'center'}">
        <el-avatar v-if="row.avatar" style="flex-shrink: 0;" :size="50" :src="row.avatar" :title="row.name" />
        <span v-if="row.nickName">{{ row.nickName }}</span>
      </div>
      <span v-else>{{ row.name }}</span>
    </template>
    <template #date="{row}">
      {{ formatTime(row.date,'YY-MM-DD HH:mm:ss') }}
    </template>
    <template #id="{row}">
      {{ row.id }}
    </template>
    <template #operation="{row}">
      <el-button v-able text type="primary" @click="handleEdit(row)">编辑</el-button>
      <el-popconfirm title="确定删除吗?"
                     @confirm="deleteScore(row)"
                     confirm-button-text="确定"
                     cancel-button-text="取消">
        <template #reference>
          <el-button v-able text type="primary">删除</el-button>
        </template>
      </el-popconfirm>
    </template>
    <!-- 筛选器插槽 -->
    <template #fields="{selectedCondition,filterConditions}">
      <div v-for="domain in selectedCondition" :key="domain.key">
        <el-form-item :label="domain.label" :prop="domain.key">
          <el-input v-if="domain.key==='name'" v-model="filterConditions.name" clearable placeholder="输入姓名或昵称"/>
          <el-input-number v-if="domain.key==='testMinute'" v-model="filterConditions.testMinute" :min="1" style="width:100%" />
          <el-date-picker
            v-if="domain.key==='date'"
            v-model="filterConditions.date"
            type="daterange"
            range-separator="-"
            start-placeholder="开始"
            end-placeholder="结束"
          />
          <el-select v-if="domain.key==='type'" v-model="filterConditions.type" placeholder="请选择" clearable>
            <el-option v-for="item in types" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
      </div>
    </template>
    <!-- 顶部自定义按钮区域 -->
    <template #outerAction>
      <el-button v-able type="primary" @click="addScore" icon="Plus" circle />
    </template>
    <!-- 自定义批量操作区 -->
    <template #defineAction>
      <el-dropdown-item v-if="selectIds.length">
        <el-popconfirm
          title="确定删除吗?"
          @confirm="delSelect"
          confirm-button-text="确定"
          cancel-button-text="取消">
          <template #reference>
            <el-button v-able text type="primary">删除</el-button>
          </template>
        </el-popconfirm></el-dropdown-item>
    </template>
  </table-easy>
  <el-drawer v-model="showDrawer" direction="rtl" size="60%">
    <template #header>
      <h4>{{isAdd?'新增':'编辑'}}成绩</h4>
    </template>
    <template #default>
      <ScoreView @cancel="cancelClick" :formData="curRow" />
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import TableEasy from '@/components/TableEasy.vue'
import ToolTip from '@/components/ToolTip.vue'
import { types } from '@/views/api/ScoreView.vue'
import ScoreView from '@/views/api/ScoreView.vue'
export interface List{
  id: number,
  date: number | string,
  rightNum: number,
  totalNum: number,
  type:string,
  name: string,
  testMinute: number
}
interface ListWraper{
  list:List[]
}
const tableType = 'student'
const list = reactive<ListWraper>({ list: [] })
const columns = [
  {
    key: 'id',
    label: 'ID',
    width: 100,
    search: false,
    sortable: false,
    isArray: false
  },
  {
    key: 'date',
    label: '日期',
    width: 129,
    search: true,
    sortable: true,
    isArray: true
  },
  {
    key: 'rightNum',
    label: '正确数',
    width: 100,
    search: false,
    sortable: true
  },
  {
    key: 'totalNum',
    label: '完成数',
    width: 80,
    search: false,
    sortable: false
  },
  {
    key: 'type',
    label: '类型',
    width: 110,
    search: true,
    sortable: true
  },
  {
    key: 'name',
    label: '姓名',
    width: 120,
    search: true,
    sortable: true
  },
  {
    key: 'testMinute',
    label: '练习时长',
    width: 80,
    search: true,
    sortable: false
  },
  {
    key: 'operation',
    label: '操作',
    width: 120,
    search: false,
    sortable: false
  }
]
// 默认筛选器
const filterArr = [
  {
    filterAttrs: [
      { key: 'name', show: true, value: [] },
      { key: 'date', show: true, value: [] },
      { key: 'type', show: true, value: [] },
      { key: 'testMinute', show: true, value: [] }
    ],
    filterName: '查询条件',
    filterType: tableType,
    id: 101,
    isCurrent: true,
    isSystem: 1,
    selected: 1
  }
]
// 改变选择
const selectIds = ref<number[]>([])
const changeSelect = (data: List[]) => {
  selectIds.value = data.map(item => item.id)
}
import { nodeService } from '@/service/index'
const total = ref(0)
const updateList = (val: any) => {
  if (!val.testMinute) {
    tableRef.value.setFilterField('testMinute', '')
  }
  searchInfo = val
  nodeService.post('/list', val).then((res: any) => {
    list.list = res.data
    total.value = res.total
  }).catch((err) => {
    console.log(err)
  })
}
// 日期格式化
import { formatTime } from '@/tools/index'
// 调用子组件翻页
const tableRef = ref()
// 删除成绩
import { ElMessage } from 'element-plus'
let searchInfo: any = {}
// 单个删除
const deleteScore = (row:List) => {
  deleteAction([row.id])
}
// 批量删除
const delSelect = () => {
  deleteAction(selectIds.value)
}
// 删除接口
const deleteAction = (id: number[]) => {
  nodeService.post(`/list/delete`, { id }).then(() => {
    if (list.list.length <= id.length) {
      // 向前翻页
      tableRef.value.previousPage(id.length)
    } else {
      updateList(searchInfo)
    }
    ElMessage.success('删除成功')
  }).catch(err => {
    ElMessage.error(err.message)
  }).finally(() => {
    tableRef.value.clearSelect()
  })
}
// 增加成绩
const showDrawer = ref(false)
const isAdd = ref(false)
const addScore = () => {
  isAdd.value = true
  showDrawer.value = true
  curRow.row = {
    id: 0,
    name: '李谦',
    date: '',
    type: '混合运算',
    rightNum: 9,
    totalNum: 10,
    testMinute: 1
  }
}
const cancelClick = () => {
  showDrawer.value = false
  updateList(searchInfo)
}
// 编辑成绩
const curRow = reactive<{row:List}>({ row: {} as List })
const handleEdit = (row: List) => {
  isAdd.value = false
  showDrawer.value = true
  curRow.row = row
}
// 处理webSocket消息
import { watch } from 'vue'
import { webSocketStore } from '@/stores/webSocket'
const socketStore = webSocketStore()
watch(() => socketStore.message, (val: any) => {
  if (val.type === 2) {
    updateList(searchInfo)
  }
}, { deep: true, immediate: true })
</script>
<style lang="less" scoped>

:deep(.el-tabs__header.is-top) {
  padding-right: 145px;
}
:deep(.el-button.is-text){
  padding:8px 2px;
}
:deep(.el-form-item__content){
  width:200px;
}
</style>
